package org.jweb.core.util.extend;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class WsUtils {
	public static final int _timeoutConnect = 30000;  // 设置连接主机超时（单位：毫秒）
	public static final int _timeoutRead = 30000;  // 设置从主机读取数据超时（单位：毫秒）
	
	public static String Send(String method, String url, String data){
		StringBuffer sb=null;
		HttpURLConnection conn=null;
		InputStream in=null;
		InputStreamReader isr=null;
		OutputStream out=null;
		try{
			URL u=new URL(url);
			conn=(HttpURLConnection)u.openConnection();
			conn.setRequestProperty("Connection", "keep-alive");
			conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setConnectTimeout(_timeoutConnect);
			conn.setReadTimeout(_timeoutRead);
			conn.setRequestMethod(method);
			if(method.equals("POST")) {
				byte[] sendbyte=data.getBytes("UTF-8");
				out=conn.getOutputStream();
				out.write(sendbyte);
			}
			
			int status=conn.getResponseCode();
			if(status==200){
				sb=new StringBuffer();
				in=conn.getInputStream();
				isr=new InputStreamReader(in, "UTF-8");
				String enc=conn.getContentEncoding();
				
				if(enc!=null && enc.equals("gzip")) {
					java.util.zip.GZIPInputStream gzin=new java.util.zip.GZIPInputStream(in);
					isr=new InputStreamReader(gzin, "UTF-8");
					
				}else{
					isr=new InputStreamReader(in, "UTF-8");
				}
				
				char[] c=new char[1024];
				int a=isr.read(c);
				while (a!=-1)
				{
					sb.append(new String(c, 0, a));
					a=isr.read(c);
				}
			}else{
				System.out.println("错误HTTP CODE:"+status);
			}
			
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			if (conn!=null)
			{
				conn.disconnect();
			}
			try{
				if(in!=null)
				{
					in.close();
				}
				if(isr!=null)
				{
					isr.close();
				}
				if(out!=null)
				{
					out.close();
				}
			}catch(IOException ex){
				ex.printStackTrace();
			}
		}
		return sb==null?null:sb.toString();
	}
	
	/*
	 * public static String objectToJson(Object obj){
		JSONObject jsonObject=JSONObject.fromObject(obj);
		String str=jsonObject.toString();
		return str;
	}*/
}
